<template>
    <div class="quote-order-list-container">
        <h2>报价单记录</h2>
        <!-- 搜索区域 -->
        <div class="search-bar">
            <el-form :model="searchForm" label-width="auto" inline>
                <el-form-item>
                    <el-input v-model="searchForm.text" placeholder="请输入单据编号/客户名称" clearable style="width: 235px;" />
                </el-form-item>

                <el-form-item label="有效日期：" prop="dateRange">
                    <el-date-picker v-model="dateRange" type="daterange" range-separator="~" start-placeholder="开始日期"
                        end-placeholder="结束日期" style="width: 390px;" @change="handleDateChange"
                        value-format="YYYY-MM-DD" />
                </el-form-item>

                <el-form-item label="报价类型：" prop="customer_type">
                    <el-select v-model="searchForm.customer_type" clearable style="width: 140px;"
                        @change="quotationTypeChange">
                        <el-option key="1" label="客户" value="1" />
                        <el-option key="2" label="客户类别" value="2" />
                        <el-option key="3" label="客户等级" value="3" />
                    </el-select>
                </el-form-item>

                <el-form-item label="报价主体：" prop="customerId">
                    <el-select v-model="searchForm.customerId" placeholder="请选择" clearable style="width: 140px;">
                        <template v-if="searchForm.customer_type == 1">
                            <el-option v-for="customer in customerList" :key="customer.code" :label="customer.name"
                                :value="customer.id" />
                        </template>
                        <template v-else-if="searchForm.customer_type == 2">
                            <el-option v-for="type in customerTypeList" :key="type.id" :label="type.name"
                                :value="type.id" />
                        </template>
                        <template v-else-if="searchForm.customer_type == 3">
                            <el-option v-for="level in customerLevelList" :key="level.id" :label="level.name"
                                :value="level.id" />
                        </template>
                    </el-select>
                </el-form-item>

                <el-form-item label="销售员：" prop="workName" v-if="!isBoss">
                    <el-input v-model="searchForm.workName" placeholder="业务员" style="width: 140px;" readonly />
                </el-form-item>

                <el-form-item label="销售员：" prop="workNumber" v-else>
                    <el-select v-model="searchForm.workNumber" placeholder="请选择" clearable style="width: 140px;">
                        <el-option v-for="salesPerson in salesPersonList" :key="salesPerson.id"
                            :label="salesPerson.name" :value="salesPerson.id" />
                    </el-select>
                </el-form-item>

                <el-form-item label="审核状态：">
                    <el-select v-model="searchForm.auditStatus" placeholder="(空)" clearable style="width: 140px;">
                        <el-option label="已保存" value="0" />
                        <el-option label="待审核" value="1" />
                        <el-option label="已审核" value="2" />
                        <el-option label="已驳回" value="3" />
                    </el-select>
                </el-form-item>

                <el-form-item label="有效期状态：">
                    <el-select v-model="searchForm.validStatus" placeholder="请选择" clearable style="width: 140px;">
                        <el-option label="有效" value="0" />
                        <el-option label="过期" value="1" />
                    </el-select>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 操作按钮区 -->
        <div v-if="!props.selectable" class="action-bar" style="float: right; margin-bottom: 15px;">
            <el-button type="primary" @click="AddQuotation">新增</el-button>
            <el-dropdown trigger="click">
                <!-- <el-button @click="submit" :disabled="isViewOnly">提交</el-button> -->
                <el-button>审核</el-button>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item>通过</el-dropdown-item>
                        <el-dropdown-item>驳回</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
            <el-button>导入</el-button>
            <el-button>导出</el-button>
            <el-button @click="batchDelete" :disabled="selectedRows.length === 0">删除</el-button>
        </div>
        <div style="clear: both;"></div>
        <!-- 主要表格 -->
        <div class="table-container">
            <el-table :data="quoteList" border stripe style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="40" align="center" />

                <el-table-column label="操作" width="140" align="center">
                    <template #default="scope">
                        <template v-if="props.selectable">
                            <el-button size="small" link  @click="selectQuotation(scope.row)">选择</el-button>
                        </template>
                        <template v-else>
                            <el-button size="small" link  @click="editQuote(scope.row)">编辑</el-button>
                            <el-button size="small" link  @click="deleteQuote(scope.row)">删除</el-button>
                        </template>
                    </template>
                </el-table-column>

                <el-table-column label="单据日期" prop="confirmDate" width="120" sortable>
                    <template #default="scope">
                        {{ formatDate(scope.row.confirmDate) }}
                    </template>
                </el-table-column>
                <el-table-column label="单据编号" prop="code" width="200" sortable />
                <!-- 报价类型列 -->
                <el-table-column label="报价类型" prop="customer_type" width="120">
                    <template #default="scope">
                        {{ customerTypeMap[scope.row.customer_type] || scope.row.customer_type }}
                    </template>
                </el-table-column>
                <el-table-column label="报价主体" prop="customerName" width="120" sortable />
                <el-table-column label="客户地址" prop="customer_address" width="180" show-overflow-tooltip />


                <!-- 审核状态列 -->
                <el-table-column label="审核状态" prop="auditStatus" width="120" sortable>
                    <template #default="scope">
                        <el-tag
                            :type="scope.row.auditStatus == '2' || scope.row.auditStatus == '0' ? 'success' : scope.row.auditStatus == '3' ? 'warning' : 'danger'"
                            size="small">
                            {{ auditStatusMap[scope.row.auditStatus] || scope.row.auditStatus }}
                        </el-tag>
                    </template>
                </el-table-column>
                <!-- 有效期状态列 -->
                <el-table-column label="有效期状态" prop="validStatus" width="120" sortable>
                    <template #default="scope">
                        <el-tag
                            :type="scope.row.validStatus == '0' ? 'success' : scope.row.validStatus == '1' ? 'warning' : 'danger'"
                            size="small">
                            {{ validStatusMap[scope.row.validStatus] || scope.row.validStatus }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="有效开始时间" prop="start_date" width="150" />
                <el-table-column label="有效结束时间" prop="end_date" width="150" />
                <el-table-column label="销售员" prop="workName" width="110" />
                <!-- 交货方式列 -->
                <el-table-column label="交货方式" prop="delivery" width="120">
                    <template #default="scope">
                        {{ deliveryMap[scope.row.delivery] || scope.row.delivery }}
                    </template>
                </el-table-column>
                <!-- <el-table-column label="关联销货订单号" prop="salesOrderCode" width="150" /> -->
                <el-table-column label="关联销货订单号" prop="salesOrderCode" width="180">
                    <template #default="scope">
                        <div v-if="scope.row.salesOrderCode">
                            <el-link v-for="code in scope.row.salesOrderCode.split(' ')" :key="code" type="primary"
                                @click="viewSalesOrder(code)" :underline="false" style="display: block;">
                                {{ code }}
                            </el-link>
                        </div>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="关联销货单号" prop="salesSlipCode" width="150" /> -->
                <el-table-column label="审核人" prop="checked_by" width="120" sortable />
                <el-table-column label="商品数量" prop="itemCount" width="110" sortable />
                <el-table-column label="金额" prop="orderPrice" width="120" sortable>
                    <template #default="scope">
                        {{ scope.row.orderPrice }}
                    </template>
                </el-table-column>
                <!-- <el-table-column label="制单人" prop="creator" width="100" />
                <el-table-column label="制单时间" prop="createTime" width="150" /> -->
                <el-table-column label="备注" prop="remarks" width="120" />
            </el-table>
        </div>

        <!-- 分页组件 -->
        <div style="float: right; padding-top: 20px;">
            <el-pagination background layout="prev, pager, next,jumper" :total="pageInfo.total"
                :page-size="pageInfo.pageSize" :current-page="pageInfo.pageNum" @current-change="changePage" />
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, defineProps, defineEmits, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()

const isBoss = sessionStorage.getItem("isBoss")
const workName = sessionStorage.getItem("name")

const quotationTypeChange = () => {
    // 当报价类型发生变化时，清空报价主体
    searchForm.customerName = ''

}
// 跳转新增报价单
const AddQuotation = () => {
    router.push({ name: 'addQuotation' })
}

const dateRange = ref([])
// 处理日期变化
const handleDateChange = (val) => {
    if (val && val.length === 2) {
        searchForm.start_date = val[0]
        searchForm.end_date = val[1]
    } else {
        searchForm.start_date = ''
        searchForm.end_date = ''
    }
}

//单据日期格式化
const formatDate = (date) => {
    if (!date) return '';
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

// 搜索表单
const searchForm = reactive({
    text: '',
    start_date: '',
    end_date: '',
    customer_type: '',
    customerId: '',
    customerName: '',
    workNumber: '',
    auditStatus: '',
    validStatus: '',
    workName: workName,
})


// 报价单数据
const quoteList = ref([])


const pageInfo = reactive({
    list: [],
    pageNum: 1,
    pageSize: 5,
    total: 0,
    pages: 1,

})
const changePage = (newPage) => {

    pageInfo.pageNum = newPage
    handleSearch()

}
// 选中行
const selectedRows = ref([])

// 搜索方法
const handleSearch = async () => {
    console.log("roleIds", sessionStorage.getItem("roleIds"))
    if (props.selectable && props.preFilterCustomerId) {
        searchForm.customerId = props.preFilterCustomerId
    }

    const queryParams = {
        pageNum: pageInfo.pageNum,
        pageSize: pageInfo.pageSize,
        text: searchForm.text,
        start_date: searchForm.start_date == '' ? null : searchForm.start_date,
        end_date: searchForm.end_date == '' ? null : searchForm.end_date,
        customer_type: searchForm.customer_type,
        workNumber: searchForm.workNumber,

    };

    if (props.selectable) {
        queryParams.customerId = props.preFilterCustomerId;
        queryParams.auditStatus = '2';
        queryParams.validStatus = '0'
    } else {
        queryParams.customerId = searchForm.customerId || undefined;
        queryParams.auditStatus = searchForm.auditStatus || undefined;
        queryParams.validStatus = searchForm.validStatus || undefined;
    }

    const response = await axios.get('/api/sales/quotationList', {
        params: queryParams
    });

    console.log("111", response.data);
    if (response.data.code == 200) {
        quoteList.value = response.data.quotationList.list
        pageInfo.total = response.data.quotationList.total
        pageInfo.pageNum = response.data.quotationList.pageNum
        pageInfo.pageSize = response.data.quotationList.pageSize
        pageInfo.pages = response.data.quotationList.pages
        console.log("222", quoteList.value);
    } else {
        ElMessage.error("查询失败")
    }
}


// 重置
const resetSearch = () => {
    Object.keys(searchForm).forEach(key => {
        if (typeof searchForm[key] === 'string') {
            searchForm[key] = ''
        } else if (Array.isArray(searchForm[key])) {
            searchForm[key] = []
        }
    })
    dateRange.value = []
}

// 表格事件
const handleSelectionChange = (val) => {
    selectedRows.value = val
}

// 修改 
const editQuote = (row) => {
    router.push({
        name: 'addQuotation',
        query: {
            code: row.code,
            id: row.id,
            from: 'edit',
            status: row.auditStatus
        }
    })
}

// 删除单个
const deleteQuote = async (row) => {
    await ElMessageBox.confirm(
        `确定要删除报价单 ${row.code} 吗？。`,
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    );

    const response = await axios.post('/api/sales/deleteQuotation', [row.id], {
        headers: {
            'Content-Type': 'application/json'
        }
    });

    if (response.data.code == 200) {
        ElMessage.success('删除成功');
        handleSearch();
    } else {
        ElMessage.error('删除失败: ' + response.data.message);
    }
};

// 删除
const batchDelete = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要删除的报价单');
        return;
    }

    // 显示确认对话框
    await ElMessageBox.confirm(
        `确定要删除选中的 ${selectedRows.value.length} 个报价单吗？此操作不可恢复。`,
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    );

    // 获取选中行的报价单编号
    const id = selectedRows.value.map(row => row.id);
    const response = await axios.post('/api/sales/deleteQuotation', id, {
        headers: {
            'Content-Type': 'application/json'
        }
    });

    if (response.data.code == 200) {
        ElMessage.success('删除成功');
        // 重新加载数据
        handleSearch();
    } else {
        ElMessage.error('删除失败: ' + response.data.message);
    }
};

const customerList = ref([
])
const customerTypeList = ref([
])
const customerLevelList = ref([
])
const salesPersonList = ref([
])
const selectOther = async () => {

    const response = await axios.get("/api/sales/selectOtherList")
    console.log("selectOther", response.data)
    if (response.data.code == 200) {
        customerLevelList.value = response.data.customerLevelList || []
        customerTypeList.value = response.data.customerTypeList || []
        customerList.value = response.data.customerList || []
    } else {
        ElMessage.error('获取客户信息失败: ' + response.data.msg)
    }
}


//销售员
const selectStaff = async () => {
    const response = await axios.get('/api/sales/selectStaff')
    if (response.data.code == 5200) {
        console.log('12', response.data)
        salesPersonList.value = response.data.saleStaffList
    } else {
        ElMessage.error(response.data.msg)
        console.error('获取销售员列表失败：', response.data.message)
    }
}
// 报价类型
const customerTypeMap = {
    '1': '客户',
    '2': '客户类别',
    '3': '客户等级'
}

// 审核状态
const auditStatusMap = {
    '0': '已保存',
    '1': '待审核',
    '2': '已审核',
    '3': '已驳回'
}

// 有效期状态
const validStatusMap = {
    '0': '有效',
    '1': '过期',
    '2': '即将到期'
}

// 交货方式
const deliveryMap = {
    '1': '快递',
    '2': '自提',
    '3': '配送'
}

//是否是源单
const props = defineProps({
    selectable: {
        type: Boolean,
        default: false
    },
    preFilterCustomerId: {
        type: [String, Number],
        default: ''
    }
})

//重新选择客户
watch(
    () => props.preFilterCustomerId,
    (newVal, oldVal) => {
        if (props.selectable && newVal !== oldVal) {
            pageInfo.pageNum = 1
            handleSearch()
        }
    }
)
const emit = defineEmits(['select'])

// 选择报价单
const selectQuotation = (row) => {
    emit('select', row)
}

const viewSalesOrder = (salesOrderCode) => {
    if (salesOrderCode) {
        router.push({
            name: 'salesOrder',
            query: {
                code: salesOrderCode,
                from: 'view'
            }
        })
    }
}

onMounted(() => {
    console.log('接收到的 preFilterCustomerId:',)
    selectStaff()
    selectOther()
    handleSearch()
})

</script>

<style scoped>
.quote-order-list-container {
    padding: 20px;
    background-color: white;
    min-height: 100vh;
}

.search-bar {
    background: white;
    padding: 15px;
    border-radius: 8px;
    margin-bottom: 15px;
}

.status-filters {
    background: white;
    padding: 10px;
    border-radius: 8px;
    margin-bottom: 15px;

}

.action-bar {
    display: flex;
    gap: 8px;
    margin-bottom: 15px;
    flex-wrap: wrap;
    background: white;
    padding: 10px;
    border-radius: 8px;

}

.action-bar.right {
    float: right;
    margin-bottom: 15px;
}

.table-container {
    background: white;
    border-radius: 8px;
    overflow: hidden;

}

.pagination {
    margin-top: 20px;
    text-align: right;
}

/* 响应式 */
@media (max-width: 768px) {

    .search-bar,
    .status-filters,
    .action-bar {
        flex-direction: column;
        gap: 10px;
    }

    .table-container {
        overflow-x: auto;
    }
}
</style>